/**
 * FileFind - ftp/shares indexing and search php engine
 * Module: persist-jpa20
 * Description: Persistence implementation with JPA 2.0
 * Copyright (c) 2003-2010 Rage Steel, www.gt2.ru
 */
package ru.ffind.persist.jpa20.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import ru.ffind.persist.jpa20.model.HostImpl;
import ru.ffind.persist.service.HostService;

/**
 * Host service.
 *
 * @author Rage Steel
 */
public class HostServiceImpl extends AbstractServiceImpl
        implements HostService {

    /**
     * {@inheritDoc}
     */
    @Override
    public List<HostImpl> findAll() {
        EntityManager entityManager = createEntityManager();
        try {
            TypedQuery<HostImpl> query = 
                    createTypedQuery(entityManager, HostImpl.class);
            return query.getResultList();
        } finally {
            entityManager.close();
        }
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public HostImpl findByNameOrNull(String hostName) {
    	HostImpl result = null;
    	EntityManager entityManager = createEntityManager();
    	try {
            CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
            CriteriaQuery<HostImpl> criteriaQuery = criteriaBuilder.createQuery(HostImpl.class);
            Root<HostImpl> host = criteriaQuery.from(HostImpl.class);
            criteriaQuery
            	.select(host)
            	.where(criteriaBuilder.equal(host.get("name"), hostName));
            
            try {
            	result = entityManager.createQuery(criteriaQuery).getSingleResult();
            } catch (NoResultException e) {
            	result = null;
            }
    	} finally {
    		entityManager.close();
    	}
    	
    	return result;
    }

}
